package com.test.springCloud.controller;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.test.springCloud.mapper.UserMapper;
import com.test.springCloud.service.MenuService;
import com.test.springCloud.service.UserService;
import com.test.springCloud.utils.JwtUtil;
import com.test.springcloud.pojo.RolePojo;
import com.test.springcloud.pojo.UserPojo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 获取路由菜单接口
 * @author luoxingfa
 * @createdate 2023/5/31 0031 11:01
 * @mood happy
 */
@CrossOrigin  //跨域
@RequestMapping("/lxf")
@Slf4j
@Controller
public class MenuController {
    @Resource
    UserService userService;

    @Resource
    MenuService menuService;

    @Autowired
    private RedisTemplate redisTemplate;

    //token签名
    private  static final String ACCESS_TOKEN="ACCESS_TOKEN";
    /**
     * 获取菜单以及菜单下的所有子菜单
     */
    @GetMapping("/getMenu")
    @ResponseBody
    public String getMenu(HttpServletRequest request){
        //装载返回结果的json
        JSONObject js = new JSONObject();
        //解析头部token
        String token = request.getHeader("token");
        String tokens = token.trim();
        //解析token,获取id
        String userId = JwtUtil.getUserId(token);
        int id = Integer.parseInt(userId);
        //查看token是否有效存在
        String accessKey=ACCESS_TOKEN+id+":"+token;
        Long expire = redisTemplate.getExpire(accessKey);
        //token未过期
        if (expire<=0){
            js.put("code",408);
            js.put("msg","token已过期，请重新登录");
        }else{
            //查询当前用户的角色id
//            UserPojo user = userService.getUserById(id);
            String res = menuService.getRouterByUserId(id);
//            Integer roleId = user.getRoleId();
//            //根据用户角色id查询当前用户所拥有的的菜单权限
//            List<RoleNavPojo> list =menuService.getMenuRootByRoleId(roleId);
//            for (int i = 0;i<list.size();i++){
//                //查询当前菜单以及旗下子菜单数据信息
//                String res = menuService.getMenu(list.get(i).getMenuId());
//                System.out.println(res);
            return res;
//            }
        }
        return  JSONObject.toJSONString(js, SerializerFeature.WriteMapNullValue);
    }
}
